package com.bstek.bdf2.core.security;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.*;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;

public class UserPasswordEncoder
  implements PasswordEncoder
{
  public static final String BEAN_ID = "bdf2.userPasswordEncoder";
  private PasswordEncoder passwordEncoder;

  /**
   * 默认使用bcrypt方式，生成的密码：{bcrypt}.密码
   * @return
   */
  public static  PasswordEncoder createPasswordEncoder()
  {
    String encodingId = "bcrypt";
    Map encoders = new HashMap();
    encoders.put(encodingId, new BCryptPasswordEncoder());
    encoders.put("argon2", new Argon2PasswordEncoder());
    encoders.put("pbkdf2", new Pbkdf2PasswordEncoder());
    encoders.put("scrypt", new SCryptPasswordEncoder());
// 以下都过期了
//    encoders.put("ldap", new org.springframework.security.crypto.password.LdapShaPasswordEncoder());
//    encoders.put("MD4", new org.springframework.security.crypto.password.Md4PasswordEncoder());
//    encoders.put("MD5", new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("MD5"));
//    encoders.put("noop", org.springframework.security.crypto.password.NoOpPasswordEncoder.getInstance());
//    encoders.put("SHA-1", new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("SHA-1"));
//    encoders.put("SHA-256",
//            new org.springframework.security.crypto.password.MessageDigestPasswordEncoder("SHA-256"));
//    encoders.put("sha256", new org.springframework.security.crypto.password.StandardPasswordEncoder());

     return new DelegatingPasswordEncoder(encodingId, encoders);
  }

  public UserPasswordEncoder()
  {
    this.passwordEncoder = new BCryptPasswordEncoder();
  }

  public String encode(CharSequence rawPassword) {
    return this.passwordEncoder.encode(rawPassword);
  }

  public boolean matches(CharSequence rawPassword, String encodedPassword)
  {
     return this.passwordEncoder.matches(rawPassword, encodedPassword);
  }

  public static void main(String[] args)  {


    BCryptPasswordEncoder pe = new BCryptPasswordEncoder();


    //加密
    String encode = pe.encode("111111");
    System.out.println(encode);
    //比较密码
    boolean matches = pe.matches("111111",encode);
    System.out.println("===================================");
    System.out.println(matches);
  }
}